package com.wengyingjian.weixin.alimama;

import com.taobao.api.ApiException;
import com.wengyingjian.weixin.common.model.TbkUrlTransferRecord;
import com.wengyingjian.weixin.dao.TbkUrlTransferDao;
import com.wengyingjian.weixin.qq.QQ2AlimamaService;
import com.wengyingjian.weixin.task.TaskExecutorHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by hzwengyingjian on 16/12/27.
 */
@Service
public class TbkUrlQQTransferService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QQ2AlimamaService qq2AlimamaService;

    @Autowired
    private TbkUrlTransferDao tbkUrlTransferDao;

    @Autowired
    private TopService topService;

    // 通过淘宝客接口获取到标题之后的处理
    private void handleTopMessageResult(String msgId, String title) {
        TbkUrlTransferRecord record = tbkUrlTransferDao.selectByTitle(title);
        // 此时还未收到QQ的恢复
        if (record == null) {
            TbkUrlTransferRecord insert = new TbkUrlTransferRecord();
            insert.setWxMsgId(msgId);
            insert.setItemTitle(title);
            tbkUrlTransferDao.insert(insert);
            return;
        }
        // 有记录，说明已收到QQ的记录
        TbkUrlTransferRecord update = new TbkUrlTransferRecord();
        update.setId(record.getId());
        update.setWxMsgId(msgId);
        tbkUrlTransferDao.updateById(update);
    }

    private String getTaobaoUrl(String content) {
        return getUrlStr(content);
    }

    public boolean isUrlContent(String content) {
        return getUrlStr(content) != null;
    }

    protected String getUrlStr(String requestContent) {
        int startIndex = requestContent.indexOf("http");
        if (startIndex == -1) {
            return null;
        }
        int endIndex = requestContent.length();
        for (int i = startIndex; i < endIndex; i++) {
            if (requestContent.charAt(i) == ' ') {
                endIndex = i;
                break;
            }
        }
        return requestContent.substring(startIndex, endIndex);
    }

    /**
     * 获取响应内容，如果内容不支持，则返回空
     *
     * @param msgId
     * @param content
     * @param isFirstAdd
     * @return
     */
    public String getResponse(String msgId, String content, boolean isFirstAdd) {
        logger.info("TbkUrlQQTransferService 尝试处理请求，msgId={},content={},isFirstAdd={}", msgId, content, isFirstAdd);
        try {
            // ===如果是第一次，则请求数据
            if (isFirstAdd) {
                // 1.请求淘宝api
                String url = getTaobaoUrl(content);
                String title = topService.getItemTitle(url);

                TbkUrlTransferRecord insert = new TbkUrlTransferRecord();
                insert.setWxMsgId(msgId);
                insert.setItemTitle(title);
                tbkUrlTransferDao.insert(insert);

                // 2.发送QQ消息
                qq2AlimamaService.sendMsg(url);
                Thread.sleep(5000L);
                return "不会走到这里..";
            }
            // ===如果不是第一次，尝试获取数据，不再请求数据，
            TbkUrlTransferRecord record = tbkUrlTransferDao.selectByMsgId(msgId);
            // 获取失败，等
            if (record.getResult() == null) {
                Thread.sleep(5000L);
                return "不会走到这里..";
            }
            // 获取成功，返回
            return record.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "不会走到这里..";
    }

    private String failed() {
        return "第三次请求未获取到数据，返回失败";
    }
}
